/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.persistence.service.DrugFormTypeService;
import com.lmx.persistence.service.DrugService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Drug;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

@JsonApiResourceRepository(Drug.class)
@Component
public class DrugRepository extends BaseRepository<Drug> {
	@Autowired
	private DrugService srv;
	@Autowired
	private DrugFormTypeService typeSrv;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(Drug.class);
	}

	@Override
	@JsonApiSave
	public Drug save(final Drug entity) {
		if (entity.getDelStatus() == ICommonConstants.DEL_STATUS_YES_1
				&& !srv.checkDelete(entity)) {
			throw new BusinessException(null,
					CommonConstants.DRUG_ERROR.IN_USE.label(), null);
		} else {
			entity.setDrugForm(typeSrv.findOne(entity.getDrugForm().getId()));
			Long tenantId = ActionContextHolder.getContext().getTenantId();
			if (entity.getId() == null
					&& this.srv.checkName(entity.getName(), entity.getDrugFactory(), tenantId)) {
				throw new BusinessException("", "4", "");
			}
			return super.save(entity);
		}

	}
}
